package com.snj.visangedu.homestudy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.snj.visangedu.HomeActivity;
import com.snj.visangedu.R;
import com.snj.visangedu.lib.Base64;
import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;

public class TeacherFragment extends Fragment implements OnClickListener {
	private final String TAG = "TeacherFragment";
	
	String subject = "math";
	String state = "0";
	String content = "개념 적용을 못하겠어요. 답변 부탁드립니다.";
	
	String currentansweringno = "";
	
	
	int begin = 0;
	int cnt = 5;
	
	ProgressDialog ProgDlg = null;
	
	Button btn_asking = null;
	Button btn_answering = null;
	Button btn_complete = null;
	
	ListView lstv_asks = null;
	AskAdapter _adapter = null;
	ArrayList<AskItem> arr_ask = new ArrayList<AskItem>();
	
	ArrayList<Bitmap> arr_bitmap = new ArrayList<Bitmap>();
	
	RelativeLayout rlly_ask = null;
	
	RelativeLayout rlly_takepic = null;
	ImageView img_takepic = null;
	
	RelativeLayout rlly_takemenu = null;
	ImageView img_takenpic = null;
	
	int takencount = 0;
	LinearLayout lily_thumbnail = null;
	ImageView[] img_thumbnail = new ImageView[3];
	
	ImageView img_ok = null;
	ImageView img_add = null;
	ImageView img_takeagain = null;
	
	
	RelativeLayout rlly_asktype = null;
	RelativeLayout rlly_asktype0 = null;
	RelativeLayout rlly_asktype1 = null;
	RelativeLayout rlly_asktype2 = null;
	
	ImageView img_pencil = null;
	TextView txt_pencil = null;
	EditText edt_detailask = null;
	
	Button btn_math = null;
	Button btn_english = null;
	Button btn_science = null;
	Button btn_korean = null;
	Button btn_society = null;
	
	
	ImageView img_ask_back = null;
	ImageView img_ask_complete = null;
	
	TextView txt_asktype = null;
	TextView txt_asktype0 = null;
	TextView txt_asktype1 = null;
	TextView txt_asktype2 = null;
	
	RelativeLayout rlly_addpicture = null;
	
	Button btn_answeringback = null;
	Button btn_answeringcomplete = null;
	RelativeLayout rlly_answeringcomplete = null;
	
	RelativeLayout rlly_answering = null;
	RelativeLayout rlly_answeringtitle = null;
	LinearLayout lily_answeringmenu = null;
	ImageView img_answering = null;
	ImageView img_asking = null;
	TextView txt_asking = null;
	
	ImageView img_answeringagain = null;
	
			
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View root = inflater.inflate(R.layout.fragment_teacher,
				container, false);
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d(TAG, "onActivityCreated");
		
		super.onActivityCreated(savedInstanceState);
		init_widget();
	}
	
	private void init_widget() {
		
		View view = getView();
		
		rlly_ask = (RelativeLayout)view.findViewById(R.id.rlly_asktype);
		
		btn_asking = (Button)view.findViewById(R.id.btn_asking);
		btn_asking.setOnClickListener(this);
		btn_asking.setSelected(true);
		
		btn_answering = (Button)view.findViewById(R.id.btn_answering);
		btn_answering.setOnClickListener(this);
		
		btn_complete = (Button)view.findViewById(R.id.btn_complete);
		btn_complete.setOnClickListener(this);
		
		btn_math = (Button)view.findViewById(R.id.btn_math);
		btn_math.setOnClickListener(this);
		btn_math.setSelected(true);
		btn_english = (Button)view.findViewById(R.id.btn_english);
		btn_english.setOnClickListener(this);
		btn_science = (Button)view.findViewById(R.id.btn_science);
		btn_science.setOnClickListener(this);
		btn_korean = (Button)view.findViewById(R.id.btn_korean);
		btn_korean.setOnClickListener(this);
		btn_society = (Button)view.findViewById(R.id.btn_society);
		btn_society.setOnClickListener(this);
		
		rlly_addpicture = (RelativeLayout)view.findViewById(R.id.rlly_addpicture);
		rlly_addpicture.setOnClickListener(this);
		
		btn_answeringback = (Button)view.findViewById(R.id.btn_answeringback);
		btn_answeringback.setOnClickListener(this);
		
		btn_answeringcomplete = (Button)view.findViewById(R.id.btn_answeringcomplete);
		btn_answeringcomplete.setOnClickListener(this);
		
		rlly_answeringcomplete = (RelativeLayout)view.findViewById(R.id.rlly_answeringcomplete);
		rlly_answeringcomplete.setOnClickListener(this);
		
		rlly_answering = (RelativeLayout)view.findViewById(R.id.rlly_answering);
		rlly_answering.setVisibility(View.GONE);
		
		rlly_answeringtitle = (RelativeLayout)view.findViewById(R.id.rlly_answeringtitle);
		
		lily_answeringmenu = (LinearLayout)view.findViewById(R.id.lily_answeringmenu);
		
		
		img_answering = (ImageView)view.findViewById(R.id.img_answering);
		img_answeringagain = (ImageView)view.findViewById(R.id.img_answeringagain);
		
		img_asking = (ImageView)view.findViewById(R.id.img_asking);
		txt_asking = (TextView)view.findViewById(R.id.txt_asking);
		txt_asking.setVisibility(View.GONE);
		 
		rlly_takepic = (RelativeLayout)view.findViewById(R.id.rlly_takepic);
		rlly_takepic.setOnClickListener(this);
		
		img_takepic = (ImageView)view.findViewById(R.id.img_takepic);
		img_takepic.setOnClickListener(this);
		
		
		lstv_asks = (ListView)view.findViewById(R.id.lstv_asks);
		
		begin = 0;
		arr_ask.clear();
		_adapter = new AskAdapter(getActivity(), this, R.layout.list_ask, arr_ask);
		
		lstv_asks.setAdapter(_adapter);
		
		
		GetAsk(subject, state);
		
		rlly_asktype = (RelativeLayout)view.findViewById(R.id.rlly_asktype);
		/*
		rlly_ask = (RelativeLayout)view.findViewById(R.id.rlly_ask);
		
		
		
		rlly_takemenu = (RelativeLayout)view.findViewById(R.id.rlly_takemenu);
		img_takenpic = (ImageView)view.findViewById(R.id.img_takenpic);
		
		
		img_thumbnail[0] = (ImageView)view.findViewById(R.id.img_thumbnail0);
		img_thumbnail[1] = (ImageView)view.findViewById(R.id.img_thumbnail1);
		img_thumbnail[2] = (ImageView)view.findViewById(R.id.img_thumbnail2);
		
		
		lily_thumbnail = (LinearLayout)view.findViewById(R.id.lily_thumbnail);
		
		img_ok = (ImageView)view.findViewById(R.id.img_ok);
		img_ok.setOnClickListener(this);
		img_add = (ImageView)view.findViewById(R.id.img_add);
		img_add.setOnClickListener(this);
		img_takeagain = (ImageView)view.findViewById(R.id.img_takeagain);
		img_takeagain.setOnClickListener(this);
		
		
		
		rlly_asktype0 = (RelativeLayout)view.findViewById(R.id.rlly_asktype0);
		rlly_asktype0.setOnClickListener(this);
		rlly_asktype1 = (RelativeLayout)view.findViewById(R.id.rlly_asktype1);
		rlly_asktype1.setOnClickListener(this);
		rlly_asktype2 = (RelativeLayout)view.findViewById(R.id.rlly_asktype2);
		rlly_asktype2.setOnClickListener(this);
		/*
		img_pencil = (ImageView)view.findViewById(R.id.img_pencil);
		txt_pencil = (TextView)view.findViewById(R.id.txt_pencil);
		edt_detailask = (EditText)view.findViewById(R.id.edt_detailask);
		edt_detailask.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				
				img_pencil.setVisibility(View.GONE);
				txt_pencil.setVisibility(View.GONE);
				
				
				rlly_asktype0.setSelected(false);
				rlly_asktype1.setSelected(false);
				rlly_asktype2.setSelected(false);
						
				content = "";
				
				return false;
			}
		});
		
		
		
		
		
		img_ask_back = (ImageView)view.findViewById(R.id.img_ask_back);
		img_ask_back.setOnClickListener(this);
		
		img_ask_complete = (ImageView)view.findViewById(R.id.img_ask_complete);
		img_ask_complete.setOnClickListener(this);
		
		
		Typeface face = Typeface.createFromAsset(getActivity().getAssets(), "fonts/NANUMBARUNGOTHICLIGHT.TTF");
		btn_math.setTypeface(face);
		btn_english.setTypeface(face);
		btn_science.setTypeface(face);
		btn_korean.setTypeface(face);
		btn_society.setTypeface(face);
		
		((TextView)view.findViewById(R.id.txt_asktype)).setTypeface(face);
		((TextView)view.findViewById(R.id.txt_question0)).setTypeface(face);
		((TextView)view.findViewById(R.id.txt_question1)).setTypeface(face);
		((TextView)view.findViewById(R.id.txt_question2)).setTypeface(face);
		edt_detailask.setTypeface(face);
		
		
		
		btn_math.setSelected(true);
		rlly_asktype0.setSelected(true);
		
		
		
		
		
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				edt_detailask.setFocusable(true);
				edt_detailask.setFocusableInTouchMode(true);
			}
		}, 1000);
		
		*/
	}
	
    
    
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	PictureCallback mPicture = new PictureCallback() {
 		public void onPictureTaken(byte[] data, Camera camera) {
 			
 			
 			Calendar calendar = Calendar.getInstance();
 			String FileName = String.format("SH%02d%02d%02d-%02d%02d%02d.jpg", 
 					calendar.get(Calendar.YEAR) % 100, calendar.get(Calendar.MONTH)+1, 
 					calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), 
 					calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
 			String path = Global.ex_storage + "/visangedu/" + FileName;

 			File file = new File(path);
 			try {
 				FileOutputStream fos = new FileOutputStream(file);
 				fos.write(data);
 				fos.flush();
 				fos.close();
 			} catch (Exception e) {
 				
 				return;
 			}
 			
 			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
 			Uri uri = Uri.parse("file://" + path);
 			intent.setData(uri);
 			getActivity().sendBroadcast(intent);

 			//Toast.makeText(getActivity(), "占쎄텢筌욊쑴�뵠 占쏙옙占쎌삢 占쎈┷占쎈�占쎈뮸占쎈빍占쎈뼄", 0).show();
 			
 			
 			camera.startPreview();
 			
 			
 			rlly_takepic.setVisibility(View.GONE);
 			//rlly_takemenu.setVisibility(View.VISIBLE);
 			
 			Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
 			
 			
 			Matrix matrix = new Matrix();
 			matrix.postRotate(90);
 			
 			Bitmap rotatedbm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
 			bm.recycle();
 			
 			arr_bitmap.clear();
 			img_answering.setImageBitmap(rotatedbm);
 			
 			arr_bitmap.add(rotatedbm);
 			
 			
 			//rlly_ask.setVisibility(View.VISIBLE);
 			rlly_answering.setVisibility(View.VISIBLE);
 			rlly_answeringtitle.setVisibility(View.GONE);
 			img_answering.setVisibility(View.VISIBLE);
 			img_asking.setVisibility(View.VISIBLE);
 			txt_asking.setVisibility(View.VISIBLE);
 			RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams)lily_answeringmenu.getLayoutParams();
 			param.height = Global.dpToPx(getActivity(), 50);
 			lily_answeringmenu.setLayoutParams(param);
 			
 			img_answeringagain.setVisibility(View.VISIBLE);
 			rlly_addpicture.setVisibility(View.GONE);
 		}
 	};

	@Override
	public void onClick(View v) {
		
		Log.d(TAG, "clicked");
		switch(v.getId())
		{
		
		case R.id.btn_ask:
			rlly_ask.setVisibility(View.GONE);
			rlly_takepic.setVisibility(View.VISIBLE);
			break;
		case R.id.img_takepic:
			//((HomeActivity)getActivity()).mSurface.mCamera.autoFocus(null);
			((HomeActivity)getActivity()).mSurface.mCamera.takePicture(null, null, mPicture);
			break;
		case R.id.rlly_takepic:
			((HomeActivity)getActivity()).mSurface.mCamera.autoFocus(null);
			break;
		case R.id.img_ok:
			rlly_takemenu.setVisibility(View.GONE);
			rlly_asktype.setVisibility(View.VISIBLE);
			break;
		case R.id.img_add:
			if(arr_bitmap.size() < 3)
			{
				rlly_takemenu.setVisibility(View.GONE);
				rlly_takepic.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.img_takeagain:
			
			img_thumbnail[0].setImageBitmap(null);
			img_thumbnail[1].setImageBitmap(null);
			img_thumbnail[2].setImageBitmap(null);
			
			img_takenpic.setImageBitmap(null);
			
			arr_bitmap.clear();
			
			rlly_takemenu.setVisibility(View.GONE);
			rlly_takepic.setVisibility(View.VISIBLE);
			break;
		case R.id.rlly_asktype0:
			rlly_asktype0.setSelected(true);
			rlly_asktype1.setSelected(false);
			rlly_asktype2.setSelected(false);
			  
			content = "문제에 사용되는 개념을 모르겠어요.";
			break;
		case R.id.rlly_asktype1:
			rlly_asktype0.setSelected(false);
			rlly_asktype1.setSelected(true);
			rlly_asktype2.setSelected(false);
			
			content = "개념 적용을 못하겠어요.";
			break;
		case R.id.rlly_asktype2:
			rlly_asktype0.setSelected(false);
			rlly_asktype1.setSelected(false);
			rlly_asktype2.setSelected(true);
			
			content = "풀이법을 모르겠어요.";
			break;
			
		case R.id.btn_math:
			
			if(subject.equals("math")) return;
			
			btn_math.setSelected(true);
			btn_english.setSelected(false);
			btn_science.setSelected(false);
			btn_korean.setSelected(false);
			btn_society.setSelected(false);
			
			subject = "math";
			
			arr_ask.clear();			
			GetAsk(subject, state);
			break;
		case R.id.btn_english:
			
			if(subject.equals("english")) return;
			
			btn_math.setSelected(false);
			btn_english.setSelected(true);
			btn_science.setSelected(false);
			btn_korean.setSelected(false);
			btn_society.setSelected(false);
			
			subject = "english";
			
			arr_ask.clear();			
			GetAsk(subject, state);
			break;
		case R.id.btn_science:
			
			if(subject.equals("science")) return;
			
			btn_math.setSelected(false);
			btn_english.setSelected(false);
			btn_science.setSelected(true);
			btn_korean.setSelected(false);
			btn_society.setSelected(false);
			
			subject = "science";
			
			arr_ask.clear();			
			GetAsk(subject, state);
			break;
		case R.id.btn_korean:
			
			if(subject.equals("korean")) return;
			
			btn_math.setSelected(false);
			btn_english.setSelected(false);
			btn_science.setSelected(false);
			btn_korean.setSelected(true);
			btn_society.setSelected(false);
			
			subject = "korean";
			
			arr_ask.clear();			
			GetAsk(subject, state);
			break;
		case R.id.btn_society:
			
			if(subject.equals("society")) return;
			
			btn_math.setSelected(false);
			btn_english.setSelected(false);
			btn_science.setSelected(false);
			btn_korean.setSelected(false);
			btn_society.setSelected(true);
			
			subject = "society";
			
			arr_ask.clear();			
			GetAsk(subject, state);
			break;
		case R.id.btn_asking:
			btn_asking.setSelected(true);
			btn_answering.setSelected(false);
			btn_complete.setSelected(false);
			
			state = "0";
			arr_ask.clear();
			GetAsk(subject, state);
			break;
		case R.id.btn_answering:
			btn_asking.setSelected(false);
			btn_answering.setSelected(true);
			btn_complete.setSelected(false);
			
			state = "1";
			arr_ask.clear();
			GetAsk(subject, state);
			break;
		case R.id.btn_complete:
			btn_asking.setSelected(false);
			btn_answering.setSelected(false);
			btn_complete.setSelected(true);
			
			state = "2";
			arr_ask.clear();
			GetAsk(subject, state);
			break;
			
		case R.id.img_ask_back:
			
			/*
			if(rlly_answering.getVisibility() == View.VISIBLE)
			{
				rlly_answering.setVisibility(View.GONE);
				rlly_answeringtitle.setVisibility(View.GONE);
				rlly_takepic.setVisibility(View.GONE);
			}
			else
			{
				rlly_asktype.setVisibility(View.VISIBLE);
				rlly_ask.setVisibility(View.VISIBLE);
				rlly_takepic.setVisibility(View.GONE);
				
				
				arr_bitmap.clear();
			}*/
			
			rlly_answering.setVisibility(View.GONE);
			rlly_asktype.setVisibility(View.VISIBLE);
 			//rlly_answeringtitle.setVisibility(View.GONE);
 			//img_answering.setVisibility(View.VISIBLE);
 			//img_asking.setVisibility(View.VISIBLE);
 			//txt_asking.setVisibility(View.VISIBLE);
			/*
 			RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams)lily_answeringmenu.getLayoutParams();
 			param.height = Global.dpToPx(getActivity(), 50);
 			lily_answeringmenu.setLayoutParams(param);
 			
 			img_answeringagain.setVisibility(View.VISIBLE);
 			rlly_addpicture.setVisibility(View.GONE);
			*/
			break;
		
		case R.id.rlly_addpicture:
			rlly_answering.setVisibility(View.GONE);
			rlly_ask.setVisibility(View.GONE);
			rlly_takepic.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_answeringback:
			rlly_answering.setVisibility(View.GONE);
			rlly_asktype.setVisibility(View.VISIBLE);
			txt_asking.setVisibility(View.GONE);
			break;
		case R.id.rlly_answeringcomplete:
		case R.id.btn_answeringcomplete:
			Log.d(TAG, "답변완료");
			UploadAnswer();	
			break;
		}
		
		
	}
	
	void UploadAnswer()
	{
		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("teacher", Global.naverid));
				postParameters.add(new BasicNameValuePair("subject", subject));
				postParameters.add(new BasicNameValuePair("no", currentansweringno));
				
				Log.d(TAG, "param : " + postParameters.toString());
            	String result = "";
            	JSONObject resultobject = null;
            	
            	
            	try {
					postParameters.add(new BasicNameValuePair("teacher", Global.naverid));
					
					for(int i=0; i<arr_bitmap.size(); i++)
	            	{
	            		ByteArrayOutputStream bao = new ByteArrayOutputStream();
						
						int max = 1024;
						
						double rate = 0;
						int newHeight = 0;
						int newWidth = 0;
						
						if(arr_bitmap.get(i).getWidth() > max)
						{
							rate = (double)(max) / (double)arr_bitmap.get(i).getWidth();
							
							newWidth = max;
							newHeight = (int)((double)arr_bitmap.get(i).getHeight() * rate);
						}
						else if(arr_bitmap.get(i).getHeight() > max)
						{
							rate = (double)(max) / (double)arr_bitmap.get(i)	.getHeight();
							
							newWidth = (int)((double)arr_bitmap.get(i).getWidth() * rate);
							newHeight = max;
						}
						
						Log.d(TAG, "new size : " + newWidth + ", " + newHeight + "(" + rate + ")");
						
						Bitmap.createScaledBitmap(arr_bitmap.get(i), newWidth, newHeight, true).compress(Bitmap.CompressFormat.JPEG, 100, bao);
	            		
	    				byte[] ba = bao.toByteArray();
	    				String ba1 = Base64.encodeBytes(ba);	    				
	    				postParameters.add(new BasicNameValuePair("answerimg" + i, ba1));
	            	}
					
					result = CustomHttpClient.executeHttpPostImage(Global.addanswerimageurl, postParameters);
					
					Log.d(TAG, "result : " + result);
					
					resultobject = new JSONObject(result);
					
					if(resultobject.getString("result").equals("success")) return "success";
									 
            	}
            	catch(Exception e)
            	{
            		e.printStackTrace();
            	}
            	
            	
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				/*
				if(result != null && result.equals("success"))
				{
					((HomeActivity)getActivity()).Show_Popup(PopupType.AskSent);
					
					rlly_asktype.setVisibility(View.GONE);
					rlly_ask.setVisibility(View.VISIBLE);
					rlly_takepic.setVisibility(View.GONE);
					GetAsk(subject, state);
					arr_bitmap.clear();	
				}
				*/
			}
			
		}.execute("");
		//
	}
	
	void GetAsk(String _subject, String _state)
	{
		new AsyncTask<String, String, String>() {

			Bitmap askimg = null;
			
			
			
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				
				ProgDlg = new ProgressDialog(getActivity());
				ProgDlg.setIndeterminate(true);
				ProgDlg.setCancelable(false);
				ProgDlg.show();
				ProgDlg.setContentView(R.layout.custom_progress);
			}



			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("student", Global.naverid));
				postParameters.add(new BasicNameValuePair("subject", params[0]));
				postParameters.add(new BasicNameValuePair("askstate", params[1]));
				
				Log.d(TAG, "param : " + postParameters.toString());
            	String result = "";
            	JSONObject resultobject = null;
            	
            	
            	try {
					result = CustomHttpClient.executeHttpPost(Global.getaskbysubjecturl, postParameters);
					
					if(result.equals("")) return  null;
					Log.d(TAG, "result : " + result);
					resultobject = new JSONObject(result);
					
					String currentpath = Global.ex_storage + "/visangedu/teacher/";
					
					Date currentdate = new Date(System.currentTimeMillis());
					currentdate.setDate(currentdate.getDate() - 7);
					
					File teacherdir = new File(currentpath);
					if(teacherdir.isDirectory())
					{
						File[] flist = teacherdir.listFiles();
						
						for(int i=0; i<flist.length; i++)
						{
							Date fdate = new Date(flist[i].lastModified());
							//if(fdate.)
						}
					}
					
					JSONArray resultarray = resultobject.getJSONArray("data");
					for(int i=0; i<resultarray.length(); i++)
					{
						JSONObject itemobject = resultarray.getJSONObject(i);
						
						ArrayList<Bitmap> arr_askimgs = new ArrayList<Bitmap>();
						
						String filename = "";
						
						
						
						for(int j=0; j<3; j++)
						{
							if(!itemobject.getString("ask_pic" + j).equals(""))
							{
								filename = itemobject.getString("ask_pic" + j).replace("/", "").replace(".jpg", ".teacher").replace(".png", ".teacher");
								
								File file = new File(currentpath + filename);
								
								//Log.d(TAG, "File path : " + currentpath + filename);
								if(file.exists())
								{										
									askimg = BitmapFactory.decodeFile(currentpath + filename);
								}
								else
								{
									askimg = CustomHttpClient.downloadBitmap(Global.godourl + "homestudy/" + itemobject.getString("ask_pic" + j));
									Global.saveBitmaptoJpeg(askimg, "visangedu/teacher", filename);
								}
								
								arr_askimgs.add(askimg);
							}
						}
						
						String state = itemobject.getString("ask_state");
						
						
						if(state.equals("0"))
						{
							state = "선택";
						}
						else
						{
							state = "답변하기";
						}
						
						arr_ask.add(new AskItem(itemobject.getString("no"), itemobject.getString("student"), "", "", itemobject.getString("content"), "", "", state, arr_askimgs, null));
						
						if(i != 0 && (i % 3) == 0)
						{
							publishProgress("");
						}
					}
					
					/*
					askimg = CustomHttpClient.downloadBitmap(Global.godourl + "homestudy/" + resultobject.getString("ask_pic0"));
					publishProgress(resultobject.getString("content"));
					//resultobject = new JSONObject(result);*/
					
            	}
            	catch(Exception e)
            	{
            		e.printStackTrace();
            	}
				return "";
			}
			
			

			@Override
			protected void onProgressUpdate(String... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
				
				
			}



			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				ProgDlg.dismiss();
				_adapter.notifyDataSetChanged();
				
			}
			
		}.execute(_subject, _state);
	}
	
	void GetAskByState(String state)
	{
		new AsyncTask<String, String, String>() {

			Bitmap askimg = null;
			
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("student", Global.naverid));
				postParameters.add(new BasicNameValuePair("subject", params[0]));
				
				
				Log.d(TAG, "param : " + postParameters.toString());
            	String result = "";
            	JSONObject resultobject = null;
            	
            	
            	try {
					result = CustomHttpClient.executeHttpPost(Global.getaskbysubjecturl, postParameters);
					
					if(result.equals("")) return  null;
					Log.d(TAG, "result : " + result);
					resultobject = new JSONObject(result);
					
					JSONArray resultarray = resultobject.getJSONArray("data");
					for(int i=0; i<resultarray.length(); i++)
					{
						JSONObject itemobject = resultarray.getJSONObject(i);
						
						ArrayList<Bitmap> arr_askimgs = new ArrayList<Bitmap>();
						
						for(int j=0; j<3; j++)
						{
							if(!itemobject.getString("ask_pic" + j).equals(""))
							{
								Log.d(TAG, "try to Download");
								try
								{
									askimg = CustomHttpClient.downloadBitmap(Global.godourl + "homestudy/" + itemobject.getString("ask_pic" + j));
									arr_askimgs.add(askimg);
								}
								catch(Exception e)
								{
									e.printStackTrace();
								}
							}
						}
						
						String state = itemobject.getString("ask_state");
						
						Log.d(TAG, "state : " + state);
						
						if(state.equals("0"))
						{
							state = "선택";
						}
						else
						{
							state = "답변하기";
						}
						
						
						arr_ask.add(new AskItem(itemobject.getString("no"), itemobject.getString("student"), "", "", itemobject.getString("content"), "", "", state, arr_askimgs, null));
						
						
						if(i != 0 && (i % 3) == 0)
						{
							publishProgress("");
						}
					}
					
					/*
					askimg = CustomHttpClient.downloadBitmap(Global.godourl + "homestudy/" + resultobject.getString("ask_pic0"));
					publishProgress(resultobject.getString("content"));
					//resultobject = new JSONObject(result);*/
					
            	}
            	catch(Exception e)
            	{
            		Log.d(TAG, "Exception");
            		e.printStackTrace();
            		
            	}
				return "";
			}
			
			

			@Override
			protected void onProgressUpdate(String... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
				
				
			}



			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				Log.d(TAG, "GET AST : POST EXECUTE");
				_adapter.notifyDataSetChanged();
				
				ProgDlg.dismiss();
				
			}
			
		}.execute(subject);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		
		
		super.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		((HomeActivity)getActivity()).StopMedia();
		
		super.onDestroy();
		
		
	}
	
	public void ChooseAsk(String no)
	{
		new AsyncTask<String, String, String>() {
			
			String _no = "";

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("teacher", Global.naverid));
				postParameters.add(new BasicNameValuePair("askid", params[0]));
				
				_no = params[0];
				
            	String result = "";
            	JSONObject resultobject = null;
            	
            	
            	try {
					result = CustomHttpClient.executeHttpPostImage(Global.choiceaskurl, postParameters);
					
					Log.d(TAG, "result : " + result);
								 
            	}
            	catch(Exception e)
            	{
            		e.printStackTrace();
            	}
            	
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				for(int i=0; i<arr_ask.size(); i++)
				{
					if(arr_ask.get(i).GetNo().equals(_no))
					{
						arr_ask.remove(i);
						break;
					}
				}
				
				btn_asking.setSelected(false);
				btn_answering.setSelected(true);
				btn_complete.setSelected(false);
				
				state = "1";
				arr_ask.clear();
				GetAsk(subject, state);
				
				
				
				_adapter.notifyDataSetChanged();
			}
			
		}.execute(no);
	}
	
	public void Answer(String no)
	{
		rlly_answering.setVisibility(View.VISIBLE);
		rlly_answeringtitle.setVisibility(View.VISIBLE);
		img_answering.setVisibility(View.GONE);
		img_answeringagain.setVisibility(View.GONE);
		
		RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams)lily_answeringmenu.getLayoutParams();
		param.height = Global.dpToPx(getActivity(), 100);
		lily_answeringmenu.setLayoutParams(param);
		
		
		
		rlly_addpicture.setVisibility(View.VISIBLE);
		currentansweringno = no;
		
		
		for(int i=0; i<arr_ask.size(); i++)
		{
			if(arr_ask.get(i).GetNo().equals(currentansweringno))
			{
				img_asking.setImageBitmap(arr_ask.get(i).GetAskImgs().get(0));
				break;
			}
		}
		
		img_asking.setVisibility(View.GONE);
	}
	
	public int ClosePopup()
	{
		if(rlly_takepic.getVisibility() == View.VISIBLE)
		{
			rlly_takepic.setVisibility(View.GONE);
			rlly_answering.setVisibility(View.VISIBLE);
			return 1;
		}
		else if(rlly_answering.getVisibility() == View.VISIBLE)
		{
			rlly_answering.setVisibility(View.GONE);
			txt_asking.setVisibility(View.GONE);
			rlly_asktype.setVisibility(View.VISIBLE);
			return 2;
		}
		return 0;
	}
}
